<script lang="ts" setup>
import type {
  OnActionClickParams,
  VxeTableGridOptions,
} from '#/adapter/vxe-table';
import type { BOMApi } from '#/models/bom/bom';

// 导入模态框实例
import { ref } from 'vue';

import { Page, useVbenModal } from '@vben/common-ui';
import { Plus } from '@vben/icons';

import { Button, message, Modal } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { $t } from '#/locales';
import { BOMModel } from '#/models/bom/bom';
import { useColumns, useGridFormSchema } from '#/views/bom/data';

import Form from './modules/form.vue';
import Import from './modules/import.vue';

const bomModel = new BOMModel();

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: Form,
  destroyOnClose: true,
});
const importModalRef = ref();
const importModalVisible = ref(false);

/**
 * 显示导入模态框
 */
const navigateToImport = () => {
  importModalVisible.value = true;
};

/**
 * 处理导入成功事件
 */
const handleImportSuccess = (data: any) => {
  console.log('导入成功:', data);
  // 显示成功提示
  message.success(
    `成功导入${data.success_count}条数据，失败${data.fail_count}条数据`,
  );

  // 如果有失败的数据，可以提供下载失败报告的功能
  if (data.fail_count > 0 && data.error_report_url) {
    Modal.confirm({
      title: '数据导入提示',
      content: '有部分数据导入失败，是否下载失败报告？',
      onOk() {
        window.open(data.error_report_url, '_blank');
      },
    });
  }

  // 导入完成后刷新表格
  refreshGrid();
};

/**
 * 处理导入错误事件
 */
const handleImportError = (error: any) => {
  console.error('导入失败:', error);
  message.error('导入失败，请重试或联系管理员');
};

/**
 * 编辑BOM
 */
function onEdit(row: BOMApi.BOM) {
  formModalApi.setData(row).open();
}

/**
 * 创建新BOM
 */
function onCreate() {
  formModalApi.setData(null).open();
}

/**
 * 删除BOM
 */
// 删除BOM
const onDelete = async (row: BOMApi.BOM) => {
  try {
    // 检查bom_id是否存在
    if (row.bom_id === undefined) {
      message.error('无效的BOM ID');
      return;
    }

    await bomModel.delete(row.bom_id);
    message.success('删除成功');
    refreshGrid();
  } catch (error) {
    message.error('删除失败');
  }
};

/**
 * 复制BOM
 */
function onCopy(row: BOMApi.BOM) {
  formModalApi.setData({ ...row, isCopy: true }).open();
}

/**
 * 查看BOM详情
 */
function onView(row: BOMApi.BOM) {
  formModalApi.setData({ ...row, isView: true }).open();
}

/**
 * 导出BOM
 */
function onExport(row: BOMApi.BOM) {
  // 检查bom_id是否存在
  if (row.bom_id === undefined) {
    message.error('无效的BOM ID');
    return;
  }

  const hideLoading = message.loading({
    content: '导出BOM',
    duration: 0,
    key: 'action_process_msg',
  });

  bomModel
    .exportBOM(row.bom_id)
    .then((response) => {
      // 处理文件下载
      const blob = new Blob([response]);
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `bom_export_${row.bom_code}_${new Date().getTime()}.xlsx`;
      link.click();
      window.URL.revokeObjectURL(url);

      message.success({
        content: '导出成功',
        key: 'action_process_msg',
      });
    })
    .catch(() => {
      hideLoading();
      message.error('导出失败');
    });
}

/**
 * 更改BOM状态
 */
function onChangeStatus(row: BOMApi.BOM) {
  // 这里可以添加状态更改的逻辑
  console.log('更改BOM状态:', row);
}

/**
 * 表格操作按钮的回调函数
 */
function onActionClick({ code, row }: OnActionClickParams<BOMApi.BOM>) {
  switch (code) {
    case 'changeStatus': {
      onChangeStatus(row);
      break;
    }
    case 'copy': {
      onCopy(row);
      break;
    }
    case 'delete': {
      onDelete(row);
      break;
    }
    case 'edit': {
      onEdit(row);
      break;
    }
    case 'export': {
      onExport(row);
      break;
    }
    case 'view': {
      onView(row);
      break;
    }
  }
}

// 表格实例
const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useGridFormSchema(),
    submitOnChange: false,
    // submitOnEnter: true,
  },
  gridEvents: {},
  gridOptions: {
    columns: useColumns(onActionClick),
    height: 'auto',
    keepSource: true,

    // 开启行选中功能
    rowConfig: {
      isCurrent: true,
      isHover: false,
    },

    // 开启分页
    pagerConfig: {
      enabled: true,
    },
    proxyConfig: {
      autoLoad: false, // 禁用自动加载数据
      ajax: {
        query: async ({ page }, formValues) => {
          return await bomModel.list({
            page: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
        },
      },
    },
    toolbarConfig: {
      custom: true,
      export: false,
      refresh: { code: 'query' },
      zoom: true,
      search: true,
    },
  } as VxeTableGridOptions,
});

/**
 * 刷新表格
 */
function refreshGrid() {
  gridApi.query();
}
</script>

<template>
  <Page auto-content-height>
    <FormModal @success="refreshGrid" />
    <Import
      ref="importModalRef"
      :visible="importModalVisible"
      @update:visible="importModalVisible = $event"
      @success="handleImportSuccess"
      @error="handleImportError"
    />
    <Grid table-title="BOM管理">
      <template #toolbar-tools>
        <Button
          type="primary"
          @click="onCreate"
          v-permission="'bom:bom:create'"
          style="order: -1; margin-right: 8px"
        >
          <Plus class="size-5" />
          {{ $t('ui.actionTitle.create') }}
        </Button>
        <Button
          type="primary"
          @click="navigateToImport"
          v-permission="'bom:bom:import'"
          style="order: -1"
        >
          {{ $t('ui.actionTitle.import') }}
        </Button>
      </template>
    </Grid>
  </Page>
</template>
